<?php

	class User extends CActiveRecord{

		public static function model($className=__CLASS__){
			return parent::model($className);
		}

		public function tableName(){
			return '{{user}}';
		}

		public function rules(){
			return array(
				array('username, password, email', 'required'),
				array('username, password, email', 'length', 'max'=>128),
				array('profile', 'safe'),
			);
		}

		public function attributeLabels(){
			return array(
				'id'=>'Id',
				'username'=>'Username',
				'password'=>'Password',
				'email'=>'Email',
				'profile'=>'Profile',
			);
		}

		public function validatePassword($password){
			$hashpass=crypt($password, $this->password);
			return $hashpass===$this->password;
		}

		public function hashPassword($password){
			$hashpass=crypt($password, $this->generateSalt());
			return $hashpass;
		}

		protected function generateSalt($cost=10){
			if(!is_numeric($cost) || $cost<4 || $cost>31){
				throw new CException(Yii::t('Соли длина'));
			}
			$rand='';
			for($i=0; $i<8; ++$i)
				$rand.=pack('S', mt_rand(0, 0xffff));
			$rand.=microtime();
			$rand=sha1($rand, TRUE);
			$salt='$2a$'.str_pad((int)$cost, 2, '0', STR_PAD_RIGHT).'$';
			$salt.=strtr(substr(base64_encode($rand), 0, 22), array('+'=>'.'));
			return $salt;
		}
	}